package com.hyt.it.ogt.data.service.pj.impl;

import java.math.BigDecimal;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.data.Constants;
import com.hyt.it.ogt.data.mapper.pj.PjDataPaperMapper;
import com.hyt.it.ogt.data.model.entity.pj.Paper;
import com.hyt.it.ogt.data.model.entity.pj.PaperItem;
import com.hyt.it.ogt.data.model.entity.pj.PaperItemFile;
import com.hyt.it.ogt.data.model.vo.pj.ItemDataVO;
import com.hyt.it.ogt.data.model.vo.pj.OptionsDataVO;
import com.hyt.it.ogt.data.model.vo.pj.PaperDataVO;
import com.hyt.it.ogt.data.model.vo.pj.ResourceAttr;
import com.hyt.it.ogt.data.model.vo.pj.TopicDataVO;
import com.hyt.it.ogt.data.service.kw.IExamPaperService;
import com.hyt.it.ogt.data.service.pj.IPjDataPaperItemFileService;
import com.hyt.it.ogt.data.service.pj.IPjDataPaperItemService;
import com.hyt.it.ogt.data.service.pj.IPjDataPaperService;
import com.hyt.it.ogt.pj.enums.PaperItemLevelEnum;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 试卷表 服务实现类
 * </p>
 *
 * @author liuqi
 * @date 2022-06-07
 */
@Service
@Slf4j
public class PjDataPaperServiceImpl extends BaseServiceImpl<PjDataPaperMapper, Paper> implements IPjDataPaperService {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
    @Resource
    private IPjDataPaperItemService iPjDataPaperItemService;
    
    @Resource
    private PjDataPaperMapper pjDataPaperMapper;

    @Autowired
    private IPjDataPaperItemFileService paperItemFileService;

    @Resource
    private IExamPaperService iExamPaperService;


    @Override
    public void savePaper(String projectId, List<PaperDataVO> papers) {
        for(PaperDataVO paperVo : papers){
            String paperId = paperVo.getPaperId();
            Integer paperVersion = paperVo.getPaperVersion();
            Integer packageVersion = paperVo.getPackageVersion();
            Paper existPaper = existPaper(projectId, paperVo.getSubjectId(), paperId, paperVersion, packageVersion);
            // 若库中存在该试卷信息，说明该试卷已经初始化过了，跳过该试卷
            if(existPaper != null){
                continue;
            }
            Paper paper = new Paper();
            paper.setId(UUIDUtils.newSortUUID());
            paper.setPaperId(paperId);
            paper.setPaperVersion(paperVo.getPaperVersion());
            paper.setPaperName(paperVo.getPaperName());
            paper.setProjectId(projectId);
            paper.setSubjectId(paperVo.getSubjectId());
            paper.setPaperScore(paperVo.getPaperScore());
            paper.setObjectiveScore(paperVo.getObjectiveItemScore());
            paper.setSubjectiveScore(paperVo.getSubjectiveItemScore());
            paper.setPackageId(paperVo.getPackageId());
            paper.setPackageVersion(paperVo.getPackageVersion());
            paper.setSort(paperVo.getSort());
            savePaper(paper);
            // 初始化试题
            initPaperItem(paperVo,paper);

            // 查询属性文件并保存
            log.info("打印查询参数： paperId:{}, paperVersion:{}", paperId, paperVersion);
            List<PaperItemFile> paperItemFileData = iExamPaperService.getPaperItemFileData(projectId, paperId, String.valueOf(paperVersion));
            if(CollectionUtil.isNotEmpty(paperItemFileData)){
                paperItemFileService.saveBatch(paperItemFileData);
            }

        }
    }

	private void savePaper(Paper paper) {
		try {
			this.save(paper);
		} catch (Exception e) {
			Throwable cause = e.getCause();
			if (cause instanceof SQLIntegrityConstraintViolationException) {
				String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
				if (Constants.SQLSTATE_23000.equals(sqlState)) {
					logger.error("试卷表中已存在主键为：【{},{},{},{},{},{}】的数据，sqlState：{}", paper.getProjectId(), paper.getSubjectId(), paper.getPaperId(), paper.getPaperVersion(), paper.getPackageVersion(),
							sqlState);
				}
			} else {
				throw e;
			}
		}
	}

    public Paper existPaper(String projectId, String subjectId, String paperId, Integer paperVersion, Integer packageVersion) {
    	return pjDataPaperMapper.existPaper(projectId, subjectId, paperId, paperVersion,packageVersion);
    }

    /**
     * 初始化试题
     * @param paperVo 试卷
     */
    private void initPaperItem(PaperDataVO paperVo, Paper paper){
        String paperId = paper.getId();
        List<TopicDataVO> topicDataList = paperVo.getTopicDataList();
        List<PaperItem> paperItems = new ArrayList<>();
        for(TopicDataVO topicDataVo: topicDataList){
            PaperItem paperItem = new PaperItem();
            paperItem.setId(UUIDUtils.newSortUUID());
            paperItem.setTopicId(topicDataVo.getTopicId());
            paperItem.setPaperId(paperId);
            paperItem.setParentId("0");
            paperItem.setItemName(topicDataVo.getTopicName());
            paperItem.setItemCode(topicDataVo.getTopicSort().toString());
            paperItem.setIsComposite(true);
            paperItem.setItemType("topic");
            paperItem.setItemLevel(PaperItemLevelEnum.TOPIC.getLevel());
            // 设置题干
            paperItem.setItemStem(topicDataVo.getTopicDescription());
            // 设置试题分数
            paperItem.setScore(topicDataVo.getTopicScore());
            // 设置排序
            paperItem.setOrderNum(topicDataVo.getTopicSort());
            paperItems.add(paperItem);
            // 初始化大题下面的小题
            initBigItem(paperItem.getId(), topicDataVo, paperItems, paperId);
            // 保存题目附件信息
            savePaperItemFile(topicDataVo, paper);
        }
        iPjDataPaperItemService.saveBatch(paperItems);
    }

    /**
     * 保存题目信息
     * @param topicDataVo
     * @param paper
     */
    private void savePaperItemFile(TopicDataVO topicDataVo, Paper paper) {
        List<ItemDataVO> itemDataVOS = topicDataVo.getItemDataList();
        for(ItemDataVO itemDataVO: itemDataVOS) {
            List<ResourceAttr> stemAttrs = itemDataVO.getStemAttrs();
            List<ResourceAttr> answerAttrs = itemDataVO.getAnswerAttrs();
            List<ResourceAttr> descriptionAttrs = itemDataVO.getDescriptionAttrs();
            // 合并集合
            List<ResourceAttr> resourceAttrList = new ArrayList<>();
            if(CollUtil.isNotEmpty(stemAttrs)){
                resourceAttrList = CollectionUtil.unionAll(resourceAttrList, stemAttrs);
            }
            if(CollUtil.isNotEmpty(answerAttrs)){
                resourceAttrList = CollectionUtil.unionAll(resourceAttrList, answerAttrs);
            }
            if(CollUtil.isNotEmpty(descriptionAttrs)){
                resourceAttrList = CollectionUtil.unionAll(resourceAttrList, descriptionAttrs);
            }

            List<PaperItemFile> paperItemFiles = new ArrayList<>();
            if(CollUtil.isNotEmpty(resourceAttrList)){
                for(ResourceAttr item : resourceAttrList) {
                    PaperItemFile paperItemFile = new PaperItemFile();
                    paperItemFile.setFileLocation(item.getType());
                    paperItemFile.setFileType(item.getFileType());
                    paperItemFile.setItemId(itemDataVO.getItemId());
                    paperItemFile.setPaperId(paper.getPaperId());
                    paperItemFile.setPaperVersion(paper.getPaperVersion());
                    paperItemFile.setSort(item.getOptionSort());
                    paperItemFile.setUrl(item.getUrl());
                    paperItemFile.setProjectId(paper.getProjectId());
                    paperItemFiles.add(paperItemFile);
                }
                paperItemFileService.saveBatch(paperItemFiles);
            }
        }
    }

    /**
     * 初始化试题
     * @param topicDataVo 大题
     * @param paperItems 试题列表
     * @param paperId 试卷id
     */
    private void initBigItem(String paperItemId, TopicDataVO topicDataVo, List<PaperItem> paperItems, String paperId) {
        List<ItemDataVO> itemDataVOS = topicDataVo.getItemDataList();
        for(ItemDataVO itemDataVO: itemDataVOS) {
            PaperItem bigItem = new PaperItem();
            bigItem.setId(UUIDUtils.newSortUUID());
            bigItem.setTopicId(itemDataVO.getItemId());
            bigItem.setPaperId(paperId);
            bigItem.setParentId(paperItemId);
            // 大题没有名称
            // itemCode
            bigItem.setItemCode(itemDataVO.getItemSort().toString());
            bigItem.setIsComposite(itemDataVO.getComposite());
            String itemType = itemDataVO.getItemType();
            bigItem.setItemType(itemType);
            bigItem.setItemLevel(PaperItemLevelEnum.SUB_ITEM.getLevel());
            bigItem.setItemViewPoint(itemDataVO.getObjective());
            bigItem.setItemStem(itemDataVO.getItemContent());
            bigItem.setAnswer(itemDataVO.getAnswer());
            bigItem.setAnalysis(itemDataVO.getDescription());
            bigItem.setOrderNum(itemDataVO.getItemSort());
            if (itemDataVO.getScore() != null) {
                bigItem.setScore(new BigDecimal(itemDataVO.getScore()));
            }
            paperItems.add(bigItem);

            if ("fill_in_blanks".equalsIgnoreCase(itemType)) {
                List<OptionsDataVO> optionsDataVOS = itemDataVO.getOptionsDataList();
                for (OptionsDataVO optionsDataVO : optionsDataVOS) {
                    PaperItem optionItem = new PaperItem();
                    optionItem.setId(UUIDUtils.newSortUUID());
                    optionItem.setTopicId(optionsDataVO.getOptionId());
                    optionItem.setPaperId(paperId);
                    optionItem.setParentId(bigItem.getId());
                    // 填空题选项没有题干
                    // optionItem.setItemName(optionsDataVO.getOptionName());
                    optionItem.setIsComposite(optionsDataVO.getComposite());
                    optionItem.setItemType("option");
                    optionItem.setItemLevel(PaperItemLevelEnum.OPTION.getLevel());
                    optionItem.setItemViewPoint(false);
                    // 填空题选项答案
                    optionItem.setAnswer(optionsDataVO.getOptionContent());
                    String optionScore = optionsDataVO.getScore();
                    optionItem.setOrderNum(optionsDataVO.getOptionSort());
                    if (StringUtils.isNotBlank(optionScore)) {
                        optionItem.setScore(new BigDecimal(optionScore));
                    }
                    optionItem.setItemCode(String.valueOf(optionsDataVO.getOptionSort()));
                    paperItems.add(optionItem);
                }
            } else {
                // 如果不是填空题
                List<ItemDataVO> childItemList = itemDataVO.getChildItemList();
                // 复合题是不是主观题的标志，默认不是，如果有小题是主观题则为是
                for (ItemDataVO childItem : childItemList) {
                    //复合题有一道主观题，这道符合题就算主观题
                    PaperItem subItem = new PaperItem();
                    subItem.setId(UUIDUtils.newSortUUID());
                    subItem.setTopicId(childItem.getItemId());
                    subItem.setPaperId(paperId);
                    subItem.setParentId(bigItem.getId());
                    // 大题没有名称
                    subItem.setItemCode(childItem.getItemSort().toString());
                    subItem.setIsComposite(childItem.getComposite());
                    String subItemType = childItem.getItemType();
                    subItem.setItemType(subItemType);
                    subItem.setItemLevel(PaperItemLevelEnum.OPTION.getLevel());
                    subItem.setItemViewPoint(childItem.getObjective());
                    subItem.setItemStem(childItem.getItemContent());
                    subItem.setAnswer(childItem.getAnswer());
                    subItem.setAnalysis(childItem.getDescription());
                    subItem.setOrderNum(childItem.getItemSort());
                    if (childItem.getScore() != null) {
                        subItem.setScore(new BigDecimal(childItem.getScore()));
                    }
                    paperItems.add(subItem);

                    if ("fill_in_blanks".equalsIgnoreCase(subItemType)) {
                        List<OptionsDataVO> optionsDataVOS = itemDataVO.getOptionsDataList();
                        for (OptionsDataVO optionsDataVO : optionsDataVOS) {
                            PaperItem optionItem = new PaperItem();
                            optionItem.setId(UUIDUtils.newSortUUID());
                            optionItem.setTopicId(optionsDataVO.getOptionId());
                            optionItem.setPaperId(paperId);
                            optionItem.setParentId(optionsDataVO.getItemId());
                            // 大题没有名称
                            // optionItem.setItemName(optionsDataVO.getOptionName());
                            optionItem.setIsComposite(optionsDataVO.getComposite());
                            optionItem.setItemType("option");
                            optionItem.setItemLevel(PaperItemLevelEnum.OPTION.getLevel());
                            optionItem.setItemViewPoint(false);
                            optionItem.setAnswer(optionsDataVO.getOptionContent());
                            optionItem.setOrderNum(optionsDataVO.getOptionSort());
                            optionItem.setItemCode(String.valueOf(optionsDataVO.getOptionSort()));
                            if (optionsDataVO.getScore() != null) {
                                optionItem.setScore(new BigDecimal(optionsDataVO.getScore()));
                            }
                            paperItems.add(optionItem);
                        }
                    }
                }
            }
        }
    }

	@Override
	public List<Paper> selectParersBySubjectId(String projectId, String subjectId) {
        return pjDataPaperMapper.selectParersBySubjectId(projectId, subjectId);
	}
}
